package iot

import (
	"errors"
	"gorm.io/gorm"
	"iot-base/auth/types"
	"iot-base/common/dbobj"
)

type (
	//TModel 物模型
	TModel dbobj.TModel

	TModelModel struct {
		db *gorm.DB
	}
)

func NewTModelModel(db *gorm.DB) *TModelModel {
	return &TModelModel{
		db,
	}
}

func (m *TModelModel) GetTModelCommByStationId(stationId string) (map[string]interface{}, error) {
	result := make(map[string]interface{})
	//tx := m.db.Model(&TModel{}).Joins("inner join things on things.model_id = t_models.uid and things.uid=?", stationId).Select("t_models.catalog_id").First(&result)
	tx := m.db.Raw("SELECT tm.catalog_id FROM t_models tm INNER JOIN things ts on tm.uid = ts.model_id and ts.uid=?", stationId).First(&result)
	return result, tx.Error
}

func (m *TModelModel) GetAllRules() ([]types.RespSelectModels, error) {
	var result []types.RespSelectModels
	err := m.db.Model(&TModel{}).Select("uid as model_id, s_name as model_name, body->>'params' as params").Find(&result).Error
	if errors.Is(err, gorm.ErrRecordNotFound) {
		return result, nil
	}
	// return  append([]types.RespSelectModels{}, result...), nil 用一定的代价切断原始切片，避免长时间的引用，导致内存无法被GC释放
	return result, nil
}

func (m *TModelModel) GetParamsByModelId(modelId string) (string, error) {
	var result string
	err := m.db.Model(&TModel{}).Select("body->>'params'").Where("uid = ?", modelId).First(&result).Error
	if errors.Is(err, gorm.ErrRecordNotFound) {
		return result, nil
	}
	return result, nil
}

func (m *TModelModel) GetStationModel() ([]map[string]interface{}, error) {
	var result []map[string]interface{}
	err := m.db.Model(&TModel{}).Select("uid as model_id,s_name as model_name,catalog_id").Where("is_station = ?", true).Find(&result).Error
	if errors.Is(err, gorm.ErrRecordNotFound) {
		return result, nil
	}
	return result, nil
}
